package com.phynos.web.main;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 登录拦截器
 * @author lupc
 *
 */
public class LoginInterceptor implements HandlerInterceptor {
	
	private static final Logger Log = Logger.getLogger(LoginInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		Log.debug("进入登录拦截器0000");
		//检查 会话是否存在		
		HttpSession session = request.getSession(false);
		if(session == null){			
			redirectToLoginView(request,response);
			return false;
		}
		//检查 会话是否有效
		Object obj = session.getAttribute(MySessionCache.KEY_SESSION_LOGIN);
		if(obj == null || !(obj instanceof MySessionCache)){
			redirectToLoginView(request,response);
			return false;
		}
		MySessionCache sc = (MySessionCache)obj;
		if(sc.checkLogin())
			return true;
		else {
			redirectToLoginView(request,response);
			return false;
		}			
	}
	
	private void redirectToLoginView(
			HttpServletRequest request,
			HttpServletResponse response) throws IOException{		
		//当前请求的URI 以及 当前请求包含参数的URI
		String fromURI = request.getRequestURI();
		Log.debug("From URI:" + fromURI);
		String fromFullURI = fromURI + 
				(request.getQueryString() == null? "":"?"+ request.getQueryString());
		Log.debug("From Full URI:" + fromFullURI);
		//登录的URI（不包含参数）
		String loginURI = request.getContextPath() + "/login";
		Log.debug("loginURI:" + loginURI);
		//包含参数的登录URI
		String uri = loginURI + "?from=" + URLEncoder.encode(fromFullURI, "utf-8");
		Log.debug("包含参数的登录URI：" + uri);
		//
		response.sendRedirect(loginURI);
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}
	
	

}
